/*!
 * \file trader_api.hpp
 * \project AI_CTP
 * 
 * \brief CTP交易API封装 - 基于wt_ctp成功实现
 */
#pragma once

#include "ctp_common.hpp"
#include <mutex>
#include <atomic>
#include <thread>
#include <unordered_map>
#include <functional>

namespace ctp_api {

// 交易回调接口
class ITraderCallback {
public:
    virtual ~ITraderCallback() = default;
    
    // 连接事件
    virtual void on_connected() {}
    virtual void on_disconnected(int reason) {}
    
    // 登录事件
    virtual void on_login_success() {}
    virtual void on_login_failed(const std::string& error_msg) {}
    
    // 订单事件
    virtual void on_order_insert(const OrderInfo& order) {}
    virtual void on_order_update(const OrderInfo& order) {}
    virtual void on_order_error(const std::string& error_msg) {}
    
    // 成交事件
    virtual void on_trade(const TradeInfo& trade) {}
    
    // 查询结果事件
    virtual void on_account_info(const AccountInfo& account) {}
    virtual void on_position_info(const PositionInfo& position) {}
    
    // 错误事件
    virtual void on_error(int error_code, const std::string& error_msg) {}
};

// CTP交易接口封装类
class TraderApi : public CThostFtdcTraderSpi {
public:
    TraderApi();
    virtual ~TraderApi();

    // 基本操作
    bool init(const std::string& broker_id, const std::string& user_id, 
              const std::string& password, const std::string& app_id = "",
              const std::string& auth_code = "", const std::vector<std::string>& front_addresses = {},
              const std::string& flow_path = "./trader_flow/");
    void release();
    bool connect();
    void disconnect();
    bool is_connected() const;
    
    // 登录相关
    bool login(const std::string& broker_id, 
               const std::string& user_id, 
               const std::string& password,
               const std::string& app_id = "",
               const std::string& auth_code = "");
    void logout();
    
    // 交易操作
    std::string insert_order(const OrderRequest& request);
    bool cancel_order(const CancelRequest& request);
    
    // 查询操作
    bool query_account();
    bool query_positions();
    bool query_orders();
    bool query_trades();
    
    // 事件回调设置
    void set_callback(std::shared_ptr<ITraderCallback> callback);
    
    // CTP回调函数重写
    void OnFrontConnected() override;
    void OnFrontDisconnected(int nReason) override;
    void OnRspAuthenticate(CThostFtdcRspAuthenticateField *pRspAuthenticateField,
                          CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin,
                       CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout,
                        CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm,
                                   CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder,
                         CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction,
                         CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount,
                               CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition,
                                 CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspQryOrder(CThostFtdcOrderField *pOrder,
                      CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspQryTrade(CThostFtdcTradeField *pTrade,
                      CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRtnOrder(CThostFtdcOrderField *pOrder) override;
    void OnRtnTrade(CThostFtdcTradeField *pTrade) override;
    void OnErrRtnOrderInsert(CThostFtdcInputOrderField *pInputOrder,
                            CThostFtdcRspInfoField *pRspInfo) override;
    void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;

private:
    // 内部辅助函数
    int generate_request_id();
    std::string generate_order_ref();
    bool is_error_response(CThostFtdcRspInfoField *pRspInfo);
    void handle_error(CThostFtdcRspInfoField *pRspInfo, const std::string& operation);
    bool create_api();
    
    // 数据转换函数
    OrderInfo convert_order(const CThostFtdcOrderField* pOrder);
    TradeInfo convert_trade(const CThostFtdcTradeField* pTrade);
    PositionInfo convert_position(const CThostFtdcInvestorPositionField* pPosition);
    AccountInfo convert_account(const CThostFtdcTradingAccountField* pAccount);
    
    // 查询队列处理
    void process_query_queue();
    void add_query_task(const std::function<void()>& task);

private:
    // CTP API相关
    CThostFtdcTraderApi* api_;
    
    // 配置参数
    std::string broker_id_;
    std::string user_id_;
    std::string password_;
    std::string app_id_;
    std::string auth_code_;
    std::vector<std::string> front_addresses_;
    std::string flow_path_;
    
    // 状态管理
    std::atomic<TradeState> state_;
    int front_id_;
    int session_id_;
    std::atomic<int> request_id_;
    std::atomic<int> order_ref_;
    
    // 事件回调
    std::shared_ptr<ITraderCallback> callback_;
    
    // 数据存储
    std::unordered_map<std::string, OrderInfo> orders_;
    std::unordered_map<std::string, PositionInfo> positions_;
    AccountInfo account_info_;
    
    // 同步和线程安全
    mutable std::mutex mutex_;
    std::mutex query_mutex_;
    
    // 查询队列相关（简化实现）
    std::thread query_thread_;
    std::atomic<bool> stop_query_thread_;
    
    // 性能统计
    std::atomic<uint64_t> total_orders_;
    std::atomic<uint64_t> total_trades_;
};

} // namespace ctp_api 